首页 > 编程笔记

Linux head和tail命令的用法

如果要截取文件中特定行数的内容,可以使用 head 和 tail 命令。

head命令

head 命令用于截取文件中开头部分的内容。如果不指定行数,默认截取前 10 行。

head 命令的语法格式如下:
head  -n   行数 
head  -行数
下面是 head 命令的示例,注意查看显示结果。
#截取文件etc.txt的前10行数据,默认是截取前10行
[root@localhost home]# head /opt/etc.txt
总用量 1.5M
drwxr-xr-x.     3 root root    101 11月 29 17:15         abrt
-rw-r--r--.     1 root root     16 11月 29 17:22         adjtime
-rw-r--r--.     1 root root   1.5K 6月   7 2013  aliases
-rw-r--r--.     1 root root    12K 11月 29 17:25         aliases.db
drwxr-xr-x.     3 root root     65 11月 29 17:17         alsa
drwxr-xr-x.     2 root root   4.0K 11月 29 17:18         alternatives
-rw-------.     1 root root    541 8月   9 2019  anacrontab
-rw-r--r--.     1 root root     55 8月   8 2019  asound.conf
-rw-r--r--.     1 root root      1 10月 31 2018  at.deny

#截取/opt/etc.txt文件的前3行数据,通过3种方式实现
#方式一:head -n 数字
[root@localhost home]# head -n 3 /opt/etc.txt
#方式二:head -数字
[root@localhost home]# head -3 /opt/etc.txt
#方式三:使用管道符“|”
[root@localhost home]# cat /opt/etc.txt  | head -3

tail命令

tail 命令用于截取文件中结尾部分的内容。如果不指定行数,默认截取后 10 行。

tail 命令的语法格式如下:
tail  -n    行数
tail  -行数
tail  -f
其中选项“-f”用于实时查看文件更新的内容,一般用于实时查看日志信息。

下面是 tail 命令的示例,注意查看显示结果。
#截取/opt/etc.txt文件的第10行数据,可以通过head命令、tail命令以及管道符一起实现
[root@localhost home]# head -10 /opt/etc.txt  | tail -n 1
-rw-r--r--.  1 root root      1 10月 31 2018 at.deny

#实时查看文件/var/log/messages,可以通过Ctrl+C快捷键终止
[root@localhost home]# tail -f /var/log/messages
……

推荐阅读

副业交流群 关注微信公众号,加入副业交流群,学习变现经验,交流各种打法。